<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://unpkg.com/axios@0.18.0/dist/axios.min.js"></script>
    <script src="https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script>
    <title>polling</title>
</head>
<body>
<div id="app">
    <button @click="longConnection">http 长连接</button>
    <button @click="stopLongConnection">关闭长连接</button>
    <p>{{time}}</p>
</div>
<script>
    window.onload=function(){
        let vm=new Vue({
            el:'#app',
            data:{
                time: '',
                eventSource: null
            },
            methods: {
                stopLongConnection() {
                   this.close()
                },
                longConnection() {
                    this.getTime()
                },
                getTime(){
                    // 实例化 EventSource 对象，并指定一个 URL 地址
                    this.eventSource = new EventSource('/longConnection'); // 使用 addEventListener() 方法监听事件
                    console.log("当前状态0", this.eventSource.readyState);
                    this.eventSource.onopen = this.onopen
                    this.eventSource.onmessage = this.onmessage
                    this.eventSource.onerror = this.onerror
                },
                onopen(){
                    console.log("链接成功.");
                    console.log("当前状态1", this.eventSource.readyState);
                },
                onmessage(res){
                    this.time = res.data
                },
                onerror(err){
                    console.log(err)
                },
                close(){
                    this.eventSource && this.eventSource.close()
                    console.log("当前状态2", this.eventSource.readyState);
                }
            }
        });
    };
</script>
</body>
</html>
